<template>
    <el-dialog :title="state.pageName" :before-close="handleClose" width="500px" top="80px" :center="true" :destroy-on-close="true" v-model="state.isShow">
        <el-card class="operate-container" shadow="never" style="display: flex; flex-wrap: wrap">
            <el-form :model="state.data" label-width="120px">
                <el-form-item label="模板编码" required>
                    <el-input v-model.number="state.data.templateCode" class="input-width" placeholder="模板编码"></el-input>
                </el-form-item>
                <el-form-item label="模板类型" required>
                    <el-select v-model="state.data.templateType">
                        <dicItemsSelectOptions dicCode="导出模板类型" data-type="Int" :withNullValue="false" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" required v-if="state.pageType == 'update'">
                    <el-select v-model="state.data.status">
                        <dicItemsSelectOptions dicCode="commStatus" data-type="Int" :withNullValue="false" />
                    </el-select>
                </el-form-item>
            </el-form>
            <el-upload :limit="1" :multiple="false" class="upload-demo" ref="upload" :action="uploadActionUrl()" :on-preview="handlePreview"
                :on-remove="handleRemove" :drag="true" :headers="state.headers" :on-success="handleSuccess" :on-error="handError" :data="state.data"
                :file-list="state.fileList" :auto-upload="false" :on-change="handleOnChange">
                <template #trigger>
                    <el-button type="primary">选取文件</el-button>
                </template>
                <el-button style="margin-left: 10px;" type="success" @click="submitUpload">保存模板</el-button>
                <el-button @click="state.fileList = []">清空文件列表</el-button>
                <template #tip>
                    <div class="el-upload__tip">最多一次上传一个文件</div>
                </template>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>

        </el-card>
    </el-dialog>
</template>
<script setup lang="ts" name="uploadTemplateDialog">

import { onMounted, reactive, ref, defineAsyncComponent, defineProps } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
const dicItemsSelectOptions = defineAsyncComponent(() => import('/@/components/dic/dicItemsSelectOptions.vue'));
import { imexportApi } from '/@/api/imexport/index';

const props = defineProps({
    refreshFunction: {
        type: Function,
        required: false,
    }
});

// import { imexportApi } from '/@/api/imexport/index';
const upload = ref();


interface TemplateModel {
    fileId: String,
    templateCode: String,
    status: Number,
    templateId: Number,
    templateType: Number,
}



const state = reactive({
    data: {},
    fileList: [],
    headers: { Authorization: Session.get('token') },
    pageType: "", pageName: "", isShow: false
});

const handleClose = function (done: () => void) {
    ElMessageBox.confirm("确认关闭？", '提示', {
        confirmButtonText: '确认',
        cancelButtonText: "取消"
    }).then(async () => {
        try {
            await props.refreshFunction();
            done();
        } catch (error: any) {
            ElMessage.error(error.msg);
        }
    });
};

const uploadActionUrl = () => {
    return (
        import.meta.env.VITE_PHOTO_API_URL + "/COMMON-SERVICE/admin/export/template/"
    );
};

const handleRemove = function (file: any, fileList: any) { };
const handleSuccess = function (response: any, file: any, fileList: any) {
    ElMessage.success("模板保存成功");
    state.isShow = false;
};

const handleOnChange = function (file: any, fileList: any) {
    state.fileList = fileList;
};


const handError = function (err: { message: string; }, file: { name: string; }, fileList: any[]) {
    ElMessage.success(file.name + "上传失败，" + err.message);
    state.fileList = file;
};

const handlePreview = (file: any) => {

};

const submitUpload = async () => {
    if (state.fileList.length <= 0 && state.pageType == "create") {
        ElMessage.success("请上传模板文件");
        return;
    }

    delete state.data["createBy"];
    delete state.data["createByName"];
    delete state.data["createDate"];
    delete state.data["updateBy"];
    delete state.data["updateByName"];
    delete state.data["updateDate"];
    if (state.pageType == "create") {
        delete state.data["templateId"];
    }

    if (state.fileList.length <= 0) {
        try {
            await imexportApi().createOrUpdateExportTemplate(state.data);
            ElMessage.success("模板保存成功");
            state.isShow = false;
        } catch (error) {
            ElMessage.error(error.msg);
        }
    } else {
        upload.value.submit();
    }
};

const initData = async function (pageType: string, data: TemplateModel) {
    if (pageType == "create") {
        let dataInit: TemplateModel = {
            status: 1,
            templateType: 10
        }
        state.fileList = [];
        state.data = dataInit;
        state.pageName = "创建模板";
    } else {
        state.data = Object.assign({}, data);
        state.pageName = "更新模板[" + data.templateCode + "]";
    }
    state.isShow = true;
    state.pageType = pageType;
    state.fileList = []
};


onMounted(() => {

});

defineExpose({
    initData
});


</script>